/*
尽可能还原 Promise 中的每一个 API, 并通过注释的方式描述思路和原理.
*/

/*
    1、promise 是一个类，执行时需要传递执行器，执行器会立即执行
    2、promise 有三种状态 等待（pending）、成功（fulfilled）、失败（failed）
    3、promise 状态确定便不可更改
*/

const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const FAILED = 'failed'

class MyPromise {
    constructor(executor){ // 执行器，
        try {
            executor(this.resolve, this.reject) // 立即执行，返回成功失败方法
        } catch (error) {
            this.reject(error)
        }
    }
    status = PENDING; // promise 状态
    value = undefined; // 成功回调数据
    reason = undefined; // 失败回调数据
    successCallback = []; // 成功回调方法
    failCallback = []; // 失败回调方法
    // 为使得 this 指向 promise 的调用者，所以这里只能用箭头函数
    resolve = value => {
        // 确定状态不可改变
        if(this.status !== PENDING) return
        // 改变状态
        this.status = FULFILLED
        // 成功回调数据赋值
        this.value = value
        //判断是否有成功缓存方法，如果有则调用
        while(this.successCallback.length) this.successCallback.shift()()
    }
    reject = reason => {
        // 确定状态不可改变
        if(this.status !== PENDING) return
        // 改变状态
        this.status = FAILED
        // 失败回调原因赋值
        this.reason = reason
        //判断是否有成功缓存方法，如果有则调用
        while(this.failCallback.length) this.failCallback.shift()()
    }
    then(successCallback, failCallback) {
        successCallback = successCallback ? successCallback : value => value
        failCallback = failCallback? failCallback : reason =>  { throw reason }
        let promise2 = new MyPromise((resolve, reject) => {
            if (this.status === FULFILLED) {
                //成功回调
                setTimeout(() => {
                    try {
                        //获取成功返回对象
                        const r = successCallback(this.value)
                        //继续链式调用
                        resolvePromise(promise2, r, resolve, reject)
                    } catch (error) {
                        reject(error)
                    }
                }, 0);
            } else if (this.status === FAILED) {
                //失败回调
                setTimeout(() => {
                    try {
                        //获取失败回调对象
                        const r = failCallback(this.reason)
                        //继续链式调用
                        resolvePromise(promise2, r, resolve, reject)
                    } catch (error) {
                        reject(error)
                    }
                }, 0);
            } else {
                //异步缓存回调方法
                this.successCallback.push(() => {
                    setTimeout(() => {
                        try {
                            const r = successCallback(this.value)
                            resolvePromise(promise2, r, resolve, reject)
                        } catch (error) {
                            reject(error)
                        }
                    }, 0);
                })
                this.failCallback.push(() => {
                    setTimeout(() => {
                        try {
                            const r = failCallback(this.reason)
                            resolvePromise(promise2, r, resolve, reject)
                        } catch (error) {
                            reject(error)
                        }
                    }, 0);
                })
            }
        })
        return promise2
    }
    finally(callback) {
        // 通过 then 获取 promise 状态
        return this.then(value => {
            //传递callback状态
            return MyPromise.resolve(callback()).then(() => value)
        }, err => {
            return MyPromise.resolve(callback()).then(() => { throw err })
        })
    }
    catch(callback) {
        return this.then(undefined, callback)
    }
    static all(array) {
        let result = [] //定义返回列表
        return new MyPromise((resolve, reject) => {
            //添加返回数据
            function addData(key, value) {
                result[key] = value
                // 如果结果数组长度跟入参长度一样则返回成功
                if(result.length === array.length){
                    resolve(result)
                }
            }
            for (let i = 0; i < array.length; i++) {
                if (array[i] instanceof MyPromise) {
                    // promise 对象处理
                    array[i].then(data => addData(i, data), err => reject(err))
                } else {
                    //普通值
                    addData(i, array[i])
                }
            }
        })
    }
    static resolve(x) {
        if (x instanceof MyPromise) {
            return x
        } else {
            return new MyPromise(resolve => resolve(x))
        }
    }
}

function resolvePromise(promise2, r, resolve, reject) {
    // 返回自己
    if (promise2 === r) {
        return reject(new Error('Chaining cycle detected for promise #<Promise>'))
    }

    if (r instanceof MyPromise) {
        // promise 对象
        r.then(resolve, reject)
    } else {
        //普通值
        resolve(r)
    }
}

module.exports =  MyPromise

